package xyz.pro5books.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhenzi.sms.ZhenziSmsClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import xyz.pro5books.mapper.BookReportMapper;
import xyz.pro5books.mapper.MsgMapper;
import xyz.pro5books.mapper.UserCollMapper;
import xyz.pro5books.mapper.UserMapper;
import xyz.pro5books.pojo.BasePojo;
import xyz.pro5books.pojo.User;
import xyz.pro5books.vo.PageResult;
import xyz.pro5books.vo.UserInfoToken;
import xyz.pro5books.vo.UserSignupInfo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BookReportMapper bookReportMapper;

    @Autowired
    private MsgMapper msgMapper;

    @Autowired
    private UserCollMapper userCollMapper;

    @Override
    public PageResult getUser(PageResult pageResult) {
        //1.定义MP分页对象，arg1页数，arg2行数
        IPage iPage = new Page(pageResult.getPageNum(),pageResult.getPageSize());
        //2.构建查询条件构造器
        QueryWrapper<User> queryWrapper =new QueryWrapper();
        //判断用户的数据是否有效，有效true,无效false
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        queryWrapper.like(flag, "name", pageResult.getQuery())
                    .eq("diff","0").or().eq("diff","1");

        //经过MP的分页查询，将所有的分页数(total/结果/页数/条数/xxx)据封装到Ipage对象中
        iPage = userMapper.selectPage(iPage,queryWrapper);

        //从分页对象中获取分页后的总记录数
        long total = iPage.getTotal();

        //从分页对象中获取分页后的结果
        List<User> rows = iPage.getRecords();
        //String online = rows.getOnline();
        return pageResult.setTotal(total).setRows(rows);
    }

    @Override
    @Transactional
    public void updateDownRight(User user) {

        userMapper.updateById(user);
    }

    @Override
    @Transactional
    public void updateUpRight(User user) {

        userMapper.updateById(user);
    }

    @Override
    public void deleteUser(Integer id) {
        userMapper.deleteById(id);

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",id);
        bookReportMapper.delete(queryWrapper);

        queryWrapper.clear();
        queryWrapper.eq("send",id);
        msgMapper.delete(queryWrapper);
        queryWrapper.clear();
        queryWrapper.eq("rece",id);
        msgMapper.delete(queryWrapper);

        queryWrapper.clear();
        queryWrapper.eq("user_id",id);
        userCollMapper.delete(queryWrapper);
    }

    @Override
    public User getUserById(Integer id) {
        User user = userMapper.selectById(id);
        return user;
    }

    @Override
    public UserInfoToken getUserTokenInfo(Integer userId) {
        User user = userMapper.selectById(userId);
        UserInfoToken userInfoToken = new UserInfoToken();
        userInfoToken.setId(user.getId())
                .setUsername(user.getUsername())
                .setDownRight(user.getDownRight())
                .setUpRight(user.getUpRight())
                .setPhone(user.getPhone())
                .setEmail(user.getEmail())
                .setCreated(user.getCreated())
                .setHeadAddr(user.getHeadAddr());
        return userInfoToken;
    }

    @Override
    @Transactional
    public void updateUser(User user) {
        userMapper.updateById(user);
    }

    @Override
    public UserInfoToken login(User user) {
        UserInfoToken userInfoToken = new UserInfoToken();
        String salt = "123abc";
        String password = user.getPassword();
        System.out.println("password = " + password);
        String md5Pass = DigestUtils.md5DigestAsHex((password+salt).getBytes());
        System.out.println("Pass+salt = " + password+"---"+salt);
        System.out.println("md5Pass = " + md5Pass);
        QueryWrapper<User>queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",user.getUsername())
                .eq("password",md5Pass);
        User userDB = userMapper.selectOne(queryWrapper);
        if(userDB == null){
            userInfoToken.setId(0);
            return userInfoToken;
        }
        userInfoToken.setId(userDB.getId()).setUsername(userDB.getUsername());
        return userInfoToken;
    }

    @Override
    public void signUp(User user) {
//        UserInfoToken userInfoToken = new UserInfoToken();
        User userInsert = new User();
        String salt = "123abc";
        String password = user.getPassword();
        System.out.println("password = " + password);
        String md5Pass = DigestUtils.md5DigestAsHex((password+salt).getBytes());
        System.out.println("Pass+salt = " + password+"---"+salt);
        System.out.println("md5Pass = " + md5Pass);
        userInsert.setUsername(user.getUsername())
                .setPassword(md5Pass)
                .setPhone(user.getPhone())
                .setRole("普通用户")
                .setEmail("xxx@xxxx.com")
                .setDownRight(true);
        userMapper.insert(userInsert);
    }

    @Override
    public void updateUsernameById(Integer userId, String username) {
        userMapper.updateById(new User().setId(userId).setUsername(username));
    }

    @Override
    public void updateEmailById(Integer userId, String email) {
        userMapper.updateById(new User().setId(userId).setEmail(email));
    }

    @Override
    public void updatePhoneById(User user) {
        userMapper.updateById(user);
    }

    @Override
    public void updatePwdById(User user) {
        User userNew = new User();

        String salt = "123abc";
        String password = user.getPassword();
        System.out.println("password = " + password);
        String md5Pass = DigestUtils.md5DigestAsHex((password+salt).getBytes());
        System.out.println("Pass+salt = " + password+"---"+salt);
        System.out.println("md5Pass = " + md5Pass);

        userNew.setId(user.getId())
                .setPassword(md5Pass);
        userMapper.updateById(userNew);
    }

    @Override
    public UserSignupInfo getUserByName(String userName) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",userName);
        User user = userMapper.selectOne(queryWrapper);

        UserSignupInfo userSignupInfo = new UserSignupInfo().setSignId(user.getId()).setNumAll(userMapper.selectCount(null));
        return userSignupInfo;
    }

    @Override
    public List getUserCreate() {
        BasePojo basePojo = new BasePojo();
        //userMapper.select(basePojo);
        return null;
    }
    //用户注册数量统计
    @Override
    public List selUserCount() {
        List list = userMapper.selUserCount();
        return list;
    }

    @Override
    public User getInfo(Integer userId) {
        QueryWrapper<User>queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",userId);
        User userInfo = userMapper.selectOne(queryWrapper);
        if(userInfo!=null){
            return userInfo;
        }
        return null;
    }

    @Override
    public void updateUserInfo(User user) {
        userMapper.updateById(user);
    }

    @Override
    public String getVerifyCode(String phoneNumber) {

        String code = String.valueOf((int)((Math.random()*9+1)*100000));

        String apiUrl = "https://sms_developer.zhenzikj.com";
        String appId = "109789";
        String appSecret = "f2cea45f-cdfb-4daf-89e0-c9faed7518f9";
        ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("number", phoneNumber);
        params.put("templateId", "6433");
        String[] templateParams = new String[1];
        templateParams[0] = code;
        params.put("templateParams", templateParams);
        try {
            String result = client.send(params);
            System.out.println("result = " + result);
            return code;
        } catch (Exception e) {
            e.printStackTrace();
            return "0000";
        }
    }

}
